package org.aom.service.security.impl;

import java.util.List;

import org.aom.dao.security.UserDao;
import org.aom.entity.security.User;
import org.aom.model.FindPWUser;
import org.aom.service.base.EntityManager;
import org.aom.service.base.ServiceException;
import org.aom.service.jms.NotifyMessageProducer;
import org.aom.service.jmx.server.ServerConfig;
import org.aom.service.security.IUserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.security.springsecurity.SpringSecurityUtils;

/**
 * 用户管理类.
 * 
 * 实现领域对象用户的所有业务管理函数.
 * 
 * 通过泛型声明继承EntityManager,默认拥有CRUD管理方法. 使用Spring annotation定义事务管理.
 * 
 * @author Saya
 */
// Spring Service Bean的标识.
@Service(value = "userManager")
// 默认将类中的所有函数纳入事务管理.
@Transactional
public class UserManager extends EntityManager<User, Long> implements
		IUserManager {
	@Autowired
	private UserDao userDao;

	@Autowired(required = false)
	private ServerConfig serverConfig; // 系统配置

	@Autowired(required = false)
	private NotifyMessageProducer notifyProducer;// JMS消息发送

	@Override
	protected UserDao getEntityDao() {
		return userDao;
	}

	/**
	 * 重载delte函数,演示异常处理及用户行为日志.
	 */
	@Override
	public void delete(Long id) {
		if (id == 1) {
			logger.warn("操作员{}尝试删除超级管理员用户", SpringSecurityUtils
					.getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}

		userDao.delete(id);
	}

	/**
	 * 取得所有用户,预加载用户的角色.
	 */
	@Transactional(readOnly = true)
	public List<User> getAllUser() {
		List<User> list = userDao.getAllUserWithRoleByDistinctHql();
		logger.trace("get {} user sucessful.", list.size());
		return list;
	}

	/**
	 * 检查用户名是否唯一.
	 * 
	 * @return loginName在数据库中唯一或等于orgLoginName时返回true.
	 */
	@Transactional(readOnly = true)
	public boolean isLoginNameUnique(String loginName, String oldLoginName) {
		return userDao.isPropertyUnique("loginName", loginName, oldLoginName);
	}

	@Transactional(readOnly = true)
	public User findUserByLoginName(String loginName) {
		return userDao.findUniqueBy("loginName", loginName);
	}

	/**
	 * 获取当前用户数量.
	 */
	@Transactional(readOnly = true)
	public Long getUserCount() {
		return userDao.findUnique(UserDao.COUNT_USERS);
	}

	/**
	 * 发送用户变更消息.
	 */
	public void sendNotifyMessage(FindPWUser findPWUser) {
		if (notifyProducer != null && serverConfig.isNotificationMailEnabled()) {
			try {
				notifyProducer.sendQueue(findPWUser);
			} catch (Exception e) {
				logger.error("消息发送失败", e);
			}
		}
	}

	/**
	 * 批量修改用户状态.
	 */
	public void disableUsers(List<Long> ids) {
		userDao.disableUsers(ids);
	}
}
